using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace Speedball2 {
  public class Electrobounces {
    private int _lightTimer;

    private Entity _entityLeft = new Entity (Game.AtariDisk, Game.AtariRamToDisk (0x4B5E));
    private Entity _entityRight = new Entity (Game.AtariDisk, Game.AtariRamToDisk (0x4B88));

    public Electrobounces () {
      _lightTimer = 0;

      // hack
      if (SpriteManager.Version == VersionEnum.Atari) {
        _entityLeft._pGfx = 0x537EA;
        _entityLeft._spriteIndex = SpriteManager.WallLeftIndex + 9;

        _entityRight._pGfx = 0x537EA;
        _entityRight._spriteIndex = SpriteManager.WallRightIndex + 9;
      }
      else if (SpriteManager.Version == VersionEnum.Amiga) {
        _entityLeft._pGfx = 0x1C0EA;
        _entityLeft._spriteIndex = 135;

        _entityRight._pGfx = 0x1C0EA;
        _entityRight._spriteIndex = 136;
      }
      else
        throw new Exception ();

      _entityLeft.Bit7_IsInvisible = true;
      _entityLeft._width = 32;
      _entityLeft._height = 32;
      _entityLeft._originXY.X = -4;

      _entityRight.Bit7_IsInvisible = true;
      _entityRight._width = 32;
      _entityRight._height = 32;
      _entityRight._originXY.X = 4;
    }

    public void CheckHit (Match match) {
      if (_lightTimer != 0) {
        _lightTimer--;
        if (_lightTimer == 0) {
          Deactivate (_entityLeft);
          Deactivate (_entityRight);
        }
      }
      if (match.EntityHoldingBall != null)
        if (match.EntityHoldingBall._pThink != 0xF078)
          return;
      if (match.EntityBall._spriteIndex > 2)
        return;
      CheckHitOne (match, _entityLeft);
      CheckHitOne (match, _entityRight);
    }

    private void CheckHitOne (Match match, Entity electrobounce) {
      Entity ball = match.EntityBall;
      if (electrobounce.UnkInRect (ball._terrainXY, 15) > 15)
        return;
      Activate (electrobounce);
      DirBits dirBits = electrobounce.GetDirBitsToTargetBetter (ball._terrainXY);
      if (dirBits.HasNoDirection)
        return;
      if (ball._terrainXY.X <= 320)
        ball._terrainXY.X = 32;
      else
        ball._terrainXY.X = 608;
      ball.Bit3_IsTeam1_IsElectrobounced = true;
      ball._dir = Entity.GetDirFromDirBits (dirBits);
      ball._velocityXY = Match.GetVelocityXYFromDir (ball._dir, 8);
      ball._opcodeIndex = 0;
      match.SetBallSpeedFromThr (match.PlayerThrower._attributes._thr);
    }

    private void Activate (Entity entity) {
      // todo
      entity.Bit7_IsInvisible = false;
      _lightTimer = 2;
    }

    private void Deactivate (Entity entity) {
      // todo
      entity.Bit7_IsInvisible = true;
    }

    public Entity EntityRight {
      get {
        return (_entityRight);
      }
    }

    public Entity EntityLeft {
      get {
        return (_entityLeft);
      }
    }
  }
}
